package com.ylyr.routerfunction.hadler;

import com.ylyr.routerfunction.exceptions.CheckException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;

/**
 * @Explain:
 * @Author: 30374
 * @Date: 2021/4/24
 */
@Configuration
@Order(-2)
public class ExceptionHandler implements WebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.BAD_REQUEST);
        response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
        String error = toStrError(ex);
        DataBuffer wrap = response.bufferFactory().wrap(error.getBytes());
        return response.writeWith(Mono.just(wrap));
    }

    private String toStrError(Throwable ex) {
        if (ex instanceof CheckException) {
            CheckException e = (CheckException) ex;
            return e.getKey() + ": 不能是" + e.getMassage();
        } else {
            ex.printStackTrace();
            return ex.toString();
        }
    }
}
